package com.huabo.cybermonitor.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblOrganizationUtil;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.JsonBean;
import com.huabo.cybermonitor.entity.*;
import com.huabo.cybermonitor.mapper.YhrPageMapper;
import com.huabo.cybermonitor.service.*;
import com.huabo.cybermonitor.service.base.CJobTaskService;
import com.huabo.cybermonitor.task.base.JobTaskService;
import com.huabo.cybermonitor.task.base.ScheduleJob;
import com.huabo.cybermonitor.util.ConstClass;
import com.huabo.cybermonitor.util.DynamicDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 模型监控-模型预警api接口
 *
 * @createTime 2022/8/11
 */

@RestController
@Slf4j
@Api(value = "模型监控-模型预警", tags = {"模型监控-模型预下所有接口"})
@RequestMapping(value = "/cyber/MxyjController")
@SuppressWarnings("all")
public class MxyjController {

    @Autowired
    IMonitorSolutionService iMonitorSolutionService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IMonitorModelService iMonitorModelService;

    @Autowired
    IMonitorModelsolutionService iMonitorModelsolutionService;

    @Autowired
    IMonitorSolutionresultService iMonitorSolutionresultService;

    @Autowired
    IAccbookService iAccbookService;

    @Autowired
    IMonitorModelresultService iMonitorModelresultService;

    @Autowired
    IWarningResultService iWarningResultService;

    @Autowired
    IMonitorSolutionModelService iMonitorSolutionModelService;

    @Autowired
    CJobTaskService cJobTaskService;

    @Autowired
    JobTaskService jobTaskService;

    @Autowired
    IStaffService iStaffService;
    @Autowired
    IMonitorSolutionStaffService iMonitorSolutionStaffService;



    @Autowired
    IIndicatorService iIndicatorService;

    @Autowired
    IMonitorExeintervalService iMonitorExeintervalService;

    @Autowired
    IMonitorSolutionRuleService iMonitorSolutionRuleService;



    @Autowired
    IAttachmentService iAttachmentService;

    @Autowired
    IWorksheetService iWorksheetService;

    @Autowired
    IBugCriterionService iBugCriterionService;

    @Autowired
    IMonitorSolutionIndicatorService  iMonitorSolutionIndicatorService;



    /**
     * 模型预警-主页
     *
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/solutions_index")
    @ApiOperation("模型预警-主页")
    public JsonBean modelssolutions_index_index(@ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = null;//staff
        Map map = new HashMap();
        try {
            staff = DealUserToken.parseUserToken(token);
            map.put("orgId", staff.getOrgid());
        } catch (Exception e) {
            return new JsonBean(200, "没有token", null);
        }
        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型预警-左边
     *
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/mxyj_left")
    @ApiOperation("模型预警-左边")
    public JsonBean mxyj_left(@ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = null;//staff
        try {
            staff = DealUserToken.parseUserToken(token);
            String orgId = staff.getCurrentOrg().getOrgid().toString();
            Map map = new HashMap();
            map.put("orgid", orgId);
            map.put("targetFrame", "mainFramex");
            return new JsonBean(200, "成功", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "failure", "没有拿到token");
    }

    /**
     * 模型预警-列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/modelsolutionmgmt")
    @ApiOperation("模型预警-列表")
    public JsonBean modelsolutionmgmt(@ApiParam(name = "solutioncode", value = "solutioncode") @RequestParam(value = "solutioncode", required = true) String solutioncode,
                                      @ApiParam(name = "solutionname", value = "solutionname") @RequestParam(value = "solutionname", required = true) String solutionname,
                                      @ApiParam(name = "orgId", value = "orgId") @RequestParam(value = "orgId", required = false) String orgId,
                                      @ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                      @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        try {
            TblStaffUtil staff = null;
            TblOrganizationUtil attribute = null;
            TblOrganizationUtil attribute1 = null;
            try {
                staff = DealUserToken.parseUserToken(token);
                //选则的机构
                attribute = staff.getCurrentOrg();
                //当前用户的机构
                attribute1 = staff.getLinkOrg();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map map = new LinkedHashMap();
            Boolean isSelect = false;

            String hbOrgEntityOrgid = staff.getCurrentOrg().getOrgid().toString(); //当前用户选择的组织hbOrgEntityOrgid
            String hbOrgNameOrgid = staff.getLinkOrg().getOrgid().toString();

            IPage<MonitorSolution> a = new Page(pageNumber, ConstClass.DEFAULT_SIZE);
            QueryWrapper<MonitorSolution> wrapper = new QueryWrapper<>();
            if (hbOrgEntityOrgid.equals(hbOrgNameOrgid)) {
                if (StringUtils.isBlank(orgId)) {
                    orgId = staff.getLinkDetp().getOrgid().toString();
                }
                wrapper.eq("type", 3);
                wrapper.eq("ORGID", new BigDecimal(orgId));
                if (StringUtils.isNotBlank(solutioncode)) {
                    wrapper.like("SOLUTIONCODE", solutioncode);
                }
                if (StringUtils.isNotBlank(solutionname)) {
                    wrapper.like("SOLUTIONNAME", solutionname);
                }


            } else {
                if (StringUtils.isBlank(orgId)) {
                    orgId = hbOrgEntityOrgid;
                }
                wrapper.eq("type", 3);
                wrapper.eq("ORGID", new BigDecimal(orgId));
                if (StringUtils.isNotBlank(solutioncode)) {
                    wrapper.like("SOLUTIONCODE", solutioncode);
                }
                if (StringUtils.isNotBlank(solutionname)) {
                    wrapper.like("SOLUTIONNAME", solutionname);
                }

            }
            iMonitorSolutionService.page(a, wrapper);

            // 加入 realName
            iStaffService.setRealName(a);

            map.put("orgId", orgId);
            map.put("solutioncode", solutioncode);
            map.put("solutionname", solutionname);
            map.put("pageBean", a);
            map.put("tblStaff", staff);


            return new JsonBean(200, "成功", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "failure", "没有拿到token");

    }




    /**
     * 模型管理-tree
     *
     * @param nodeId
     * @param type
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/findOrganizationByTreeAll")
    @ApiOperation("模型管理-tree")
    public JsonBean mxgl_findOrganizationByTree(@ApiParam(name = "nodeId", value = "nodeId") @RequestParam("nodeId") BigDecimal nodeId,
                                                @ApiParam(name = "type", value = "type") @RequestParam("type") String type,
                                                @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = null;
        try {
            staff = DealUserToken.parseUserToken(token);
            BigDecimal orgId = staff.getCurrentOrg().getOrgid();

            String json = "";
            if (null == nodeId) {
                nodeId = orgId;
            }
            //树问题
            if (StringUtils.isNotBlank(type)) {
                List<Tree> list = iOrganizationService.getNodeAll(nodeId);
                json = JSONObject.toJSONString(list);
            } else {
                List<Tree> list = iOrganizationService.getNodeAll(nodeId);

                json = JSONObject.toJSONString(list);

            }
            return new JsonBean(200, "成功", json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "failure", "没有拿到token");
    }

    /**
     * 模型预警-跳转添加
     *
     * @param
     * @return
     */
    @PostMapping(value = "/mxjk/to_modelsolution_add")
    @ApiOperation("模型预警-跳转添加")
    public JsonBean toModelSolutionAdd(@ApiParam(name = "orgId", value = "orgId") @RequestParam(value = "orgId", required = true) String orgId,
                                       @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = null;//staff
        try {
            staff = DealUserToken.parseUserToken(token);
            String Orgid = staff.getCurrentOrg().getOrgid().toString();
            Map map = new HashMap(2);
            map.put("orgId", orgId);
            map.put("tblStaff", staff);
            return new JsonBean(200, "成功", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "failure", "没有拿到token");
    }

    /**
     * 模型预警-保存
     *
     * @param
     * @return
     * @throws ParseException
     */
    @PostMapping(value = "/mxjk/modelsolution_add")
    @ApiOperation("模型预警-保存")
    public JsonBean modelSolutionAdd(
            @ApiParam(name = "solution", value = "solution") @RequestBody() MonitorSolution solution,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws ParseException {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        solution.setCreatedate(LocalDateTime.now());
        solution.setRunstatus(new BigDecimal(0));
        solution.setType(new BigDecimal(3));
        iMonitorSolutionService.save(solution);
        Map map = new HashMap();
        //为页面查找区域显隐藏赋值
        map.put("selectedid", solution.getSolutionid());
        map.put("orgId", solution.getOrgid());// solution.getOrganization().getOrgid() 老代码
        map.put("solution", solution);
        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型预警-跳转修改
     * 以及详情采用同一个方法
     *
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/to_modelsolution_modify")
    @ApiOperation("模型预警-跳转修改(详情页面采用同一个方法)")
    public JsonBean to_modelsolution_modify(@ApiParam(name = "infoid", value = "infoid") @RequestParam("infoid") String infoid,
                                            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        MonitorSolution solution = iMonitorSolutionService.getById(infoid);
        QueryWrapper qw=new  QueryWrapper();
        qw.eq("SOLUTIONID",infoid);
        List<MonitorSolutionModel> list=iMonitorSolutionModelService.list(qw);
        List<MonitorModel> list3=new ArrayList<MonitorModel>();
        if(list.size()>0) {
            List<BigDecimal> list2 = list.stream().map(x -> x.getModelid()).collect(Collectors.toList());
            QueryWrapper<MonitorModel> qw1 = new QueryWrapper<MonitorModel>();
            qw1.in("modelid", list2);
            list3 = iMonitorModelService.list(qw1);
        }
        Map map = new HashMap();
        //map.put("orgId", orgId);
        map.put("viewType", infoid);
        if (solution != null) {
            map.put("solution", solution);
            map.put("models",list3);
        }
        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型预警-添加模型-列表
     *
     * @param
     * @return
     */
    @PostMapping(value = "/mxjk/modellistSelector")
    @ApiOperation("模型预警-添加模型-列表")
    public JsonBean modellistSelector(@ApiParam(name = "orgId", value = "orgId",defaultValue = "127634") @RequestParam("orgId") String orgId,
                                      @ApiParam(name = "modelid", value = "modelid") @RequestParam(value="modelid",required = false) String modelid,
                                      @ApiParam(name = "solutionid", value = "solutionid",defaultValue = "796669") @RequestParam("solutionid") String solutionid,
                                      @ApiParam(name = "pageNumber", value = "pageNumber",defaultValue = "1") @RequestParam("pageNumber") Integer pageNumber,
                                      @ApiParam(name = "limit", value = "limit",defaultValue = "20") @RequestParam(value="limit",required = false) Integer limit,
                                      @ApiParam(name = "modelids", value = "modelids") @RequestParam(value="modelids",required = false) Integer modelids,
                                      @ApiParam(name = "OrgidOrgid", value = "OrgidOrgid") @RequestParam(value = "OrgidOrgid",required = false) String OrgidOrgid,
                                      @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = null;
        try {
            staff = DealUserToken.parseUserToken(token);
            String Orgid = staff.getCurrentOrg().getOrgid().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (orgId == null) {
            orgId = OrgidOrgid;
        }
        IPage<MonitorModel> a = new Page<>(pageNumber, limit);
        QueryWrapper<MonitorModel> wrapper = new QueryWrapper<>();
        wrapper.eq("MODELSTATUS", "启用");
        wrapper.eq("SUBSYSTEM", 1);
        wrapper.eq("ORGID", orgId);
        if (modelid != null && !"".equals(modelid)) {
            wrapper.like("MODELID", modelid);
        }
        if (modelids != null && !"".equals(modelids)) {
            wrapper.notIn("MODELID", modelids);

        }
        wrapper.orderByAsc("MODELID");
        Map map = new HashMap();
        map.put("pageBean", iMonitorModelService.page(a, wrapper));
        map.put("orgId", orgId);
        map.put("modelid", modelid);
        map.put("solutionid", solutionid);
        return new JsonBean(200, "成功", map);
    }


    /**
     * 模型预警-保存模型
     *
     * @param request
     * @return
     */
    @ApiOperation("模型预警-添加模型列表-选定")
    @PostMapping(value = "/mxyj/add_model")
    public  JsonBean add_model(
            @ApiParam(name = "souceid", value = "souceid",defaultValue = "128887") @RequestParam(value="souceid")String souceid,
            @ApiParam(name = "modelid", value = "modelid",defaultValue = "129086,129088,129135") @RequestParam(value="modelid")String modelid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

		/*if (modelid != null && souceid != null) {
			TblMonitorSolution monitorSolution = tblMonitorSolutionService.findOne(souceid);
			TblMonitorModel model = tblMonitorModelService.findOne(modelid);
			Set<TblMonitorModel> models = monitorSolution.getTblMonitorSolutionModels();
			if (models != null && models.size() > 0) {
				for (TblMonitorModel tblMonitorModel : models) {
					if (tblMonitorModel.getModelid() != model.getModelid()) {
						monitorSolution.getTblMonitorSolutionModels().add(model);
					}
				}
			} else {
				monitorSolution.getTblMonitorSolutionModels().add(model);
			}
			tblMonitorSolutionService.modify(monitorSolution);
		}*/
        if (modelid != null && souceid != null) {
            String[] modelids = modelid.split(",");
            this.iMonitorSolutionService.addyjModel(modelids,souceid);
            return new JsonBean(200, "成功", null);
        }
        return new JsonBean(-1, "modelid,souceid传值有null值", null);
    }

    /**
     * 模型预警-修改
     *
     * @param
     * @return
     */
    @PostMapping(value = "/mxjk/modelsolution_modify")
    @ApiOperation("模型预警-修改")
    public JsonBean modelsolution_modify(@ApiParam(name = "solutionid", value = "solutionid") @RequestParam("solutionid") String solutionid,
                                         @ApiParam(name = "orgId", value = "orgId") @RequestParam(value="orgId",required = false) String orgId,
                                         @ApiParam(name = "solutioncode", value = "solutioncode") @RequestParam(value="solutioncode",required = false) String solutioncode,
                                         @ApiParam(name = "solutionname", value = "solutionname") @RequestParam("solutionname") String solutionname,
                                         @ApiParam(name = "solutionstatus", value = "solutionstatus") @RequestParam(value="solutionstatus",required = false) String solutionstatus,
                                         @ApiParam(name = "memo", value = "memo") @RequestParam(value="memo",required = false) String memo,
                                         @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) throws ParseException {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        MonitorSolution solution = new MonitorSolution();
        QueryWrapper qw = new QueryWrapper();
        qw.eq("SOLUTIONID", solutionid);
        if (solutionid != null && !"".equals(solutionid)) {
            solution = iMonitorSolutionService.getOne(qw);
        }
        solution.setSolutioncode(solutioncode);
        solution.setSolutionname(solutionname);
        solution.setSolutionstatus(solutionstatus);
        solution.setMemo(memo);
        iMonitorSolutionService.updateById(solution);
        Map map = new HashMap();
        map.put("orgId", orgId);
        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型预警-删除
     *
     * @param
     * @return
     */
    @PostMapping(value = "/mxjk/modelsolution_del")
    @ApiOperation("模型预警-删除")
    public JsonBean modelsolution_del(@ApiParam(name = "selectedid", value = "selectedid") @RequestParam("selectedid") String selectedid,
                                      @ApiParam(name = "orgId", value = "orgId") @RequestParam(value="orgId",required = false) String orgId,
                                      @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {

        if(!ConstClass.checkToken(token)){
            return ConstClass.tokenFailure();
        }
        Map map = new HashMap();
        if (selectedid != null) {
            MonitorSolution monitorSolution = this.iMonitorSolutionService.getById(selectedid);
            //map.put("orgId", monitorSolution.getOrgid());
            QueryWrapper qw = new QueryWrapper();
            qw.eq("RULESOLUTIONID",selectedid);
            iMonitorExeintervalService.remove(qw);
            QueryWrapper qw1 = new QueryWrapper();
            qw1.eq("SOLUTIONID",selectedid);
            iMonitorSolutionRuleService.remove(qw1);

            QueryWrapper qw2 = new QueryWrapper();
            qw2.eq("SOLUTIONID",selectedid);
            iMonitorSolutionStaffService.remove(qw2);
            iMonitorSolutionModelService.remove(qw2);
            iMonitorSolutionIndicatorService.remove(qw2);
            iMonitorSolutionService.removeById(selectedid);


        }

        map.put("orgId", orgId);
        map.put("selectedid", selectedid);
        return new JsonBean(200, "成功", map);
    }

    /**
     * 修改状态
     *
     * @param 、
     * @return
     * @author SongXiangYing
     * @date 2016年1月14日 下午5:12:19
     */
    @GetMapping(value = "/mxjk/modelsolutionUpdateStatus")
    @ApiOperation("修改状态")
    public JsonBean modelsolutionUpdateStatus(@ApiParam(name = "solutionid", value = "solutionid",defaultValue ="123456" ) @RequestParam("solutionid") BigDecimal solutionid,
                                              @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        MonitorModelsolution solution = iMonitorModelsolutionService.getById(solutionid);
        System.out.println(solution);
        System.out.println(solutionid);
        if(Objects.isNull(solution)){
            return new JsonBean(200, "表中没有此数据", solutionid);
        }
        String status = solution.getSolutionstatus();
        if (status.equalsIgnoreCase("启用")) {
            solution.setSolutionstatus("停用");
        } else if (status.equalsIgnoreCase("停用")) {
            solution.setSolutionstatus("启用");
        }
        Map map = new HashMap();
        iMonitorModelsolutionService.updateById(solution);
        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型预警 ---执行结果
     *
     * @param
     * @param
     * @return
     * @author SongXiangYing
     * @date 2016年1月28日 下午10:09:58
     */
    @GetMapping(value = "/mxjk/resultmodelyj")
    @ApiOperation("模型预警 ---第一级页面-结果")
    public JsonBean resultmodelyj(@ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                  @ApiParam(name = "modelid", value = "modelid") @RequestParam("modelid") String modelid,
                                  @ApiParam(name = "fhtype", value = "fhtype") @RequestParam("fhtype") String fhtype,
                                  @ApiParam(name = "orgId", value = "orgId") @RequestParam("orgId") String orgId,
                                  @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        QueryWrapper<MonitorSolutionresult> wrapper = new QueryWrapper<>();
        IPage<MonitorSolutionresult> a = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        wrapper.eq("solutionid", new BigDecimal(modelid));
        wrapper.eq("source", MonitorSolutionresult.ZX);
        wrapper.orderByDesc("saveTime");

        a=iMonitorSolutionresultService.page(a, wrapper);

        iStaffService.setRealNameForMonitorSolutionresult(a);
        Map map = new LinkedHashMap();
        map.put("orgId", orgId);
        map.put("fhtype", fhtype);
        map.put("orgId", orgId);
        map.put("modelid", modelid);
        map.put("pageBean", a);
        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型预警 ---执行结果---详细结果
     *
     * @param
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/resultmodellist")
    @ApiOperation("模型预警 ---第二级结果页面-结果")
    public JsonBean resultModelList(@ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                    @ApiParam(name = "modelId", value = "modelId") @RequestParam("modelId") String modelId,
                                    @ApiParam(name = "modelid", value = "modelid") @RequestParam("modelid") String modelid,
                                    @ApiParam(name = "fhtype", value = "fhtype") @RequestParam("fhtype") String fhtype,
                                    @ApiParam(name = "orgId", value = "orgId") @RequestParam("orgId") String orgId,
                                    @ApiParam(name = "solutionResultId", value = "solutionResultId") @RequestParam("solutionResultId") BigDecimal solutionResultId,
                                    @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        IPage<MonitorSolutionresult> a = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);
        Map map = new HashMap();
        map.put("solutionResultId", solutionResultId);
        map.put("modelId", modelId);
        map.put("modelid", modelid);
        map.put("fhtype", fhtype);
        map.put("orgId", orgId);
        map.put("pageBean", iMonitorModelService.ShowPage(new BigDecimal(modelId), a));
        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型管理 ---结果
     *
     * @param pageNumber
     * @param modelId
     * @param
     * @return
     * @author SongXiangYing
     * @date 2016年1月29日 上午11:05:50
     */
    @GetMapping(value = "/mxjk/resultmodelinfo")
    @ApiOperation("模型管理 ---结果--多模块通用(模型预警与模型管理)")
    public JsonBean resultmodelInfo(@ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                    @ApiParam(name = "modelId", value = "modelId传soluId时为modelId,不传soluId时为resultid") @RequestParam(value = "modelId") BigDecimal modelId,
                                    @ApiParam(name = "soluId", value = "soluId非必填项,看模块") @RequestParam(value = "soluId", required = false) BigDecimal soluId,
                                    @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        MonitorModelresult modelResult = null;
        BigDecimal mid = null;
        if (null != soluId) {

            QueryWrapper<MonitorModelresult> wrapper = new QueryWrapper<>();
            wrapper.eq("solutionresultid", soluId);
            wrapper.eq("modelid", modelId);
            modelResult = iMonitorModelresultService.getOne(wrapper);
            if (modelResult != null) {
                mid = modelResult.getResultid();
            }
        } else {
            modelResult = iMonitorModelresultService.getById(modelId);
            mid = modelId;
        }
        String signid = modelResult.getSignid();
        MonitorModel model = iMonitorModelService.getById(modelResult.getModelid());
        List<String> list = new ArrayList<String>();
        if (StringUtils.isNotBlank(model.getModelstep1())) {
            list.add("第一步");
        }
        if (StringUtils.isNotBlank(model.getModelstep2())) {
            list.add("第二步");
        }
        if (StringUtils.isNotBlank(model.getModelstep3())) {
            list.add("第三步");
        }
        if (StringUtils.isNotBlank(model.getModelstep4())) {
            list.add("第四步");
        }
        if (StringUtils.isNotBlank(model.getModelstep5())) {
            list.add("第五步");
        }
        Map map = new HashMap();
        map.put("signid", signid);
        map.put("modelId", mid);
        map.put("soluId", soluId);
        map.put("list", list);


        return new JsonBean(200, "成功", map);
    }

    /**
     * 模型管理 --详细结果
     *
     * @param index
     * @param
     * @param modelId
     * @return
     * @author SongXiangYing
     * @date 2016年1月29日 上午11:06:08
     */
    @GetMapping(value = "/mxjk/resultmodelinfo1/{index}/{signId}/{modelId}/{source}")
    @ApiOperation("模型管理 --详细结果")
    public JsonBean resultmodelInfo1(@ApiParam(name = "index", value = "index") @PathVariable("index") String index,
                                     @ApiParam(name = "signId", value = "signId") @PathVariable("signId") String signId,
                                     @ApiParam(name = "modelId", value = "modelId") @PathVariable("modelId") BigDecimal modelId,
                                     @ApiParam(name = "source", value = "source") @PathVariable("source") Integer source,
                                     @ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", name = "pageNumber", defaultValue = "1") Integer pageNumber,
                                     @ApiParam(name = "fhtype", value = "fhtype") @RequestParam("fhtype") String fhtype,
                                     @ApiParam(name = "orgId", value = "orgId") @RequestParam("orgId") String orgId,
                                     @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws SQLException {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        MonitorModel model = null;
        if (source.equals(MonitorModelresult.ZJ)) {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("RESULTID", modelId);
            MonitorModelresult modelResult = iMonitorModelresultService.getOne(qw);
            model = iMonitorModelService.getById(modelResult.getModelid());
//            model = iMonitorModelService.getById(659770);
        } else {
            QueryWrapper<MonitorModelresult> wrapper = new QueryWrapper<>();
            wrapper.eq("resultId", modelId);
            wrapper.like("signid", iWarningResultService.getLast() + "_%");
            List<MonitorModelresult> list = iMonitorModelresultService.list(wrapper);
            if (list.size() > 0) {
                model = iMonitorModelService.getById(modelId.toString());
                signId = list.get(0).getSignid();
                index = list.get(0).getIsdata().toString();
            }
        }

        String tableName = "ZNJK_MX_" + model.getModelid().toString() + "_" + index;
        Accbook acctbook = iAccbookService.getById(model.getConnectionstrings());
        if (Objects.isNull(acctbook)) {
            return new JsonBean(500, "通过连库没有找到帐簿!!" + model.getConnectionstrings(), null);
        }
        DynamicDataSource dynamicDataSource = new DynamicDataSource(acctbook.getAcctid());
        Map<String, Object> cols = dynamicDataSource.getData(tableName, signId, pageNumber, ConstClass.DEFAULT_SIZE, "");
        Map<String, Object> map = new HashMap<>(6);
        map.put("column", cols.get("column"));
        map.put("pageBean", cols.get("data"));
        map.put("index", index);
        map.put("fhtype", fhtype);
        map.put("orgId", orgId);
        map.put("modelId", modelId);
        map.put("signId", signId);
        map.put("modelId", modelId);
        map.put("source", source);
        map.put("bookId", acctbook.getAcctid());
        return new JsonBean(200, "成功", map);
    }

    @Autowired
    YhrPageMapper yhrPageMapper;
    /**
     * 模型预警 --详细结果
     *
     * @param
     * @param
     * @param modelId
     * @return
     * @author SongXiangYing
     * @date 2016年1月29日 上午11:06:08
     */
    @GetMapping(value = "/mxjk/resultmodelinfo/{modelId}/{soluId}")
    @ApiOperation("模型预警 --第三级详细结果页面")
    public JsonBean resultmodelInfo2(@ApiParam(name = "modelId", value = "modelId",required = true) @PathVariable("modelId") BigDecimal modelId,
                                     @ApiParam(name = "soluId", value = "soluId",required = true) @PathVariable("soluId") BigDecimal soluId,
                                     @ApiParam(name = "modelIds", value = "modelIds") @RequestParam(value="modelIds",required = false) BigDecimal modelIds,
                                     @ApiParam(name = "fhtype", value = "fhtype") @RequestParam(value="fhtype",required = false) BigDecimal fhtype,
                                     @ApiParam(name = "orgId", value = "orgId") @RequestParam(value="orgId",required = false) BigDecimal orgId,
                                     @ApiParam(name = "modelid", value = "modelid") @RequestParam(value="modelid",required = false) BigDecimal modelid,
                                     @ApiParam(name = "solutionResultId", value = "solutionResultId") @RequestParam(value="solutionResultId",required = false) BigDecimal solutionResultId,
                                     @ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber",required = false ) Integer pageNumber,
                                     @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        String sql = "select * " +
                "from TBL_MONITOR_MODELRESULT t " +
                "         left join TBL_MONITOR_SOLUTIONRESULT TMS on t.SOLUTIONRESULTID = TMS.SOLUTIONRESULTID " +
                "where tms.SOLUTIONRESULTID ="+modelId+" and t.MODELID="+soluId;
        Map<String,Object> modelResult = yhrPageMapper.queryBySql(sql);

        MonitorModel model = iMonitorModelService.getById(new BigDecimal(modelResult.get("MODELID").toString()));
        System.out.println(model+"==>");
        int index = 0;
        if (StringUtils.isNotBlank(model.getModelstep1())) {
            index = 1;
            if (StringUtils.isNotBlank(model.getModelstep2())) {
                index = 2;
                if (StringUtils.isNotBlank(model.getModelstep3())) {
                    index = 3;
                    if (StringUtils.isNotBlank(model.getModelstep4())) {
                        index = 4;
                        if (StringUtils.isNotBlank(model.getModelstep5())) {
                            index = 5;
                        }
                    }
                }
            }
        }
        String tableName = "ZNJK_MX_" + model.getModelid().toString() + "_" + index;
        Accbook acctbook = iAccbookService.getById(model.getConnectionstrings());
        if (Objects.isNull(acctbook)) {
            return new JsonBean(500, "通过连库没有找到帐簿!!" + model.getConnectionstrings(), null);
        }
        Map<String, Object> map = new HashMap();
        try {
            DynamicDataSource dynamicDataSource = new DynamicDataSource(acctbook.getAcctid());
            Map<String, Object> cols = dynamicDataSource.getData(tableName, modelResult.get("RESULTID").toString(), pageNumber, ConstClass.DEFAULT_SIZE, "");
            map.put("column", cols.get("column"));
            map.put("pageBean", cols.get("data"));
            map.put("soluId", soluId);
            map.put("modelId", modelId);
            map.put("modelIds", modelIds);
            map.put("fhtype", fhtype);
            map.put("orgId", orgId);
            map.put("modelid", modelid);
            map.put("solutionResultId", solutionResultId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new JsonBean(200, "成功", map);
    }

    /**
     * 验证模型是否被预警使用
     *
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/model_info_is")
    @ApiOperation("验证模型是否被预警使用")
    public JsonBean model_info_is(@ApiParam(name = "incid", value = "incid") @RequestParam("incid") String incid,
                                  @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        int num = 0;
        if (incid != null && !"".equals(incid)) {
            MonitorModel in = iMonitorModelService.getById(incid);
            QueryWrapper<MonitorSolution> wrapper = new QueryWrapper<>();
            wrapper.eq("modelid", incid);
            List<MonitorSolution> list2 = iMonitorSolutionService.list(wrapper);
            num = list2.size();
            if (String.valueOf(in.getRunstatus()).equals("2")) {
                num = 2;
            }
        }
        return new JsonBean(200, "成功", num);
    }

    /**
     * 模型预警-执行
     *
     * @param
     * @return
     */
    @GetMapping(value = "/mxjk/modelsolution_execute")
    @ApiOperation("模型预警-执行")
    public JsonBean modelsolution_execute(@ApiParam(name = "id", value = "id") @RequestParam("id") String id,
                                          @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil staff = null;
        try {
            staff = DealUserToken.parseUserToken(token);
            String Orgid = staff.getCurrentOrg().getOrgid().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MonitorSolution modelsolution = iMonitorSolutionService.getById(id);
        QueryWrapper<MonitorSolutionModel> wrapper = new QueryWrapper<>();
        wrapper.eq("solutionid", id);

        List<MonitorSolutionModel> list2 = iMonitorSolutionModelService.list(wrapper);
        if (list2.size() > 0) {
            if (modelsolution.getSolutionstatus().equals("启用")) {
                if (modelsolution.getRunstatus().equals(new BigDecimal("1"))) {
                    return new JsonBean(200, "执行中，请稍等！", "执行中，请稍等！");
                }
                List<MonitorSolution> list = new ArrayList<>();
                list.add(modelsolution);
                ScheduleJob job = null;
                try {
                    Staff staff1 = iStaffService.getById(staff.getStaffid());
                    job = cJobTaskService.mxyjTaskExec(list, staff1, "", MonitorSolutionresult.ZX);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                    try {
                        jobTaskService.changeStatus(job, "stop");
                    } catch (SchedulerException e1) {
                        e1.printStackTrace();
                    }
                }
                return new JsonBean(200, "成功", "");
            }
            return new JsonBean(200, "请先启用模型！", "请先启用模型！");
        }
        return new JsonBean(200, "模型预警缺少模型规则！", "模型预警缺少模型规则！");
    }

    @ApiOperation("模型预警-启用")
    @PostMapping(value = "/gzjk/solution/solutionUpdateStatus")
    public JsonBean solutionUpdateStatus(
            @ApiParam(name = "solutionid", value = "solutionid",defaultValue = "201006") @RequestParam("solutionid")BigDecimal  solutionid,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        TblStaffUtil staff = DealUserToken.parseUserToken(token);
        MonitorSolution solution = iMonitorSolutionService.getById(solutionid);
        if(solution==null){
            return new JsonBean(-1,"id在表中不存在",solutionid);
        }
        if (solution.getStaffid().equals(staff.getStaffid())) {
            if (null != solution) {
                String status = solution.getSolutionstatus();
                if (status.equalsIgnoreCase("启用")) {
                    solution.setSolutionstatus("停用");
                } else if (status.equalsIgnoreCase("停用")) {
                    solution.setSolutionstatus("启用");
                }
                iMonitorSolutionService.updateById(solution);
                return new JsonBean(200,"修改成功",solution);
            }
        }
        return new JsonBean(-1,"权限不足",null);
        // ModelAndView mv = new ModelAndView();
        // mv.setViewName("redirect:/znjk/gzjk/rule/solutionmgmt?orgId="+orgId+"&pageNumber="+pageNumber);
        //
        // return mv;
    }
}
